package offer_test_20;

import java.math.BigDecimal;

//：实现函数 double Power（double base，int exponent），
//求base的exponent次方。不得使用库函数，同时不需要考虑大数问题。
public class eleven_Power {
	public static void main(String[] args) throws Exception {
		double rs=power(1.2,3);
		System.out.println(rs);
	}

	public static double power(double base, int exp) throws Exception {
		double rs = 0.0;
		if (equal(base, 0.0) && exp < 0) {
			throw new Exception("0的负数次幂没有意义");
		}
		if (exp < 0) {
			exp = -exp;
		}
		rs=multi(base, exp);
		if(exp<0) rs=1/rs;
		return rs;
	}

	public static double multi(double base, int exp) {
		double rs=1.0;
		if (exp == 0)
			return 0.0;
		if (exp == 1)
			return base;
		if((exp&1)==0){
			rs=multi(base,exp>>1)*multi(base,exp>>1);
		}else{
			rs=multi(base,exp>>1)*multi(base,exp>>1)*base;
		}
		return rs;
	}

	public static boolean equal(double one, double two) {
		BigDecimal bd_one = new BigDecimal(one);
		BigDecimal bd_two = new BigDecimal(two);
		if (bd_one.equals(bd_two)) {
			return true;
		} else {
			return false;
		}
	}
}
